<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <div class="content">

          <div class="progressHint" v-if="hint">
            <NIcon size="20" class="iconStyle">
              <ErrorRound />
            </NIcon>
            <div style="white-space: pre-wrap" v-html="hint"></div>
          </div>
          <div class="progress">
            <div style="display:flex; margin-right: 10rem;">
              <NIcon :size="20" class="iconStyle">
                <ApprovalFilled />
              </NIcon>
              <span>审批流程</span>
            </div>
            <span style="font-size: 18rem;flex: 1;" :style="{ color: !workFlowList ? 'red' : '#79bb92' }">
              {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
            </span>
          </div>

          <div class="content_cen">
            <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules" :label-width="100"
              :model="formValue" style="width: 350rem" label-align="right">
              <NFormItem label="项目名称:" path="projectName">
                <NInput placeholder="请输入项目名称" class="commonWidth" v-model:value="formValue.projectName"
                  :allow-input="stopNull" />
              </NFormItem>
              <NFormItem label="预算金额:" path="budgetAmount">
                <NInput placeholder="请输入预算金额" class="commonWidth" v-model:value="formValue.budgetAmount"
                  :allow-input="onlyFloatNumber" @blur="handleAmountBlur">
                  <template #suffix>
                    元
                  </template>
                </NInput>
              </NFormItem>
              <NFormItem label="经费出处:" path="fundingSource">
                <NInput placeholder="请输入经费出处" v-model:value="formValue.fundingSource" class="commonWidth"
                  :allow-input="stopNull" />
              </NFormItem>
              <NFormItem label="采购内容:" path="procurementContent">
                <NInput placeholder="请输入采购内容" v-model:value="formValue.procurementContent" class="commonWidth"
                  type="textarea" style="height: 130rem" :allow-input="stopNull" />
              </NFormItem>
              <NFormItem label="附件:" path="fileId">
                <VUpload :file-list="fileList" @getList="handleUploadList" />
              </NFormItem>
            </NForm>
          </div>
        </div>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
          <template #icon>
            <img :src="VBackImg" style="width: 25rem; height: 25rem" />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="background-color: #5faab1;" @click="confirm(true)" :loading="loading"
          v-if="formValue.entityId">
          保存草稿
        </NButton>
        <NButton type="primary" @click="confirm(false)" :loading="loading" v-if="formValue.entityId">
          提交申请
        </NButton>
      </NSpace>
    </div>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againConfirm" title="保存提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{ contentContent }}
      </div>
    </VDialogContent>
  </NModal>

  <NModal :auto-focus="false" v-model:show="modalVisibleSure">
    <VDialogContentOnlySure @close="modalVisibleSure = false" @submit="modalVisibleSure = false" title="提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        该金额已超过30万,请走党委会流程
      </div>
    </VDialogContentOnlySure>
  </NModal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { NSpace, NForm, NInput, NFormItem, NButton, NScrollbar, useMessage, NModal, NIcon, type FormInst } from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import VDialogContentOnlySure from '@/views/OA/Common/DialogContentOnlySure.vue'
import { useRoute } from 'vue-router'
import VBackImg from '@/assets/images/back.png'
import { ApprovalFilled } from '@vicons/material'
import { ErrorRound } from '@vicons/material'
import VUpload from '@/views/OA/Common/Upload.vue'

const route = useRoute()
const tags = useTagStore().tags
const message = useMessage()
const props = defineProps({
  title: { type: String, default: () => '采购需求申请' },
  id: { type: [Number, String], default: () => null },
  flag: { type: [Number, String], default: () => null }
})

const formValue = reactive<Record<string, any>>({
  draftFlag: null, //草稿状态
  entityId: null, //流程实体id
  projectName: null,
  budgetAmount: null,
  procurementContent: null,
  fileId: null,
  procurementType: null,
  fundingSource: null
})
const rules = {
  projectName: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请填写项目名称')
      if (value.length > 100) return new Error('项目名称字数不得超过100')
      return true
    },
  },
  procurementContent: {
    required: false,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (value && value.length > 500) return new Error('采购内容字数不得超过500')
      return true
    },
  },
  fundingSource: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请填写经费出处')
      if (value.length > 500) return new Error('经费出处字数不得超过500')
      return true
    },
  },
  budgetAmount: {
    required: false,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (value && value > 99999999) return new Error('金额不得超过99999999元')
      return true
    },
  }
}

// 预算金额失焦
const handleAmountBlur = () => {
  if (formValue.budgetAmount < 100000) return getWorkFlow('A0524')
  if (formValue.budgetAmount < 300000) return getWorkFlow('A0567')
  else return getWorkFlow('A0568')
}
// 两位小数数字
const onlyFloatNumber = (value: string) => {
  var regA = /^\d*\.{0,1}\d{0,2}$/
  return !value || regA.test(value)
}
// 去除空格
const stopNull = (value: string) => !value.startsWith(' ') && !value.endsWith(' ')
// 获取流程id
const hint = ref()
const workFlowList = ref(' ')
const getWorkFlow = async (code: string) => {
  formValue.procurementType = code
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'workFlow',
    override: {
      params: {
        functionCode: code
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  formValue.entityId = res.data.entityId
  hint.value = res.data.remark
  workFlowList.value = res.data.workFlowList?.length ? res.data.workFlowList?.map((it: any) => it).join(' → ') : null
  if (formValue.budgetAmount >= 300000) modalVisibleSure.value = true
}
// 附件
const fileList: any = ref([])
const handleUploadList = (v: any) => formValue.fileId = v
// 获取详情
const getInfo = async () => {
  const [error, res] = await sendRequest({
    module: 'procure',
    api: 'procureItem',
    uri: {
      id: props.id as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  fileList.value = res.data.fileList
  Object.keys(formValue).map((it: any) => formValue[it] = res.data[it])
  handleAmountBlur()
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (tags.length == 0) router.push({ path: '/OA/Workbench/UserDesktop' })
  else history.back()
}
// 提交完跳转我的提交
const goSubmit = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (formValue.draftFlag) return router.push({ path: '/OA/UserCenter/Drafts' })
  router.push({ path: '/OA/UserCenter/Submit' })
}
// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const modalVisible = ref(false)
const contentContent = ref()
const modalVisibleSure = ref(false)
const confirm = (status: boolean) => {
  formValue.draftFlag = status
  formRef.value?.validate(async (err) => {
    if (err) return
    contentContent.value = status ? '您确定要保存草稿吗？' : ' 您确定要提交申请吗？'
    if (formValue.budgetAmount >= 300000) return modalVisibleSure.value = true
    modalVisible.value = true
  })
}
// 提交
const againConfirm = async () => {
  if (props.id && !props.flag) {
    const [error, res] = await sendRequest({
      module: 'procure',
      api: 'procureUpdate',
      override: {
        data: {
          ...formValue,
          id: props?.id
        }
      }
    })
    if (error) return message.error(error.message)
    message.success(res.msg)
    goSubmit()
  } else {
    const [error, res] = await sendRequest({
      module: 'procure',
      api: 'procureSave',
      override: {
        data: formValue
      }
    })
    if (error) return message.error(error.message)
    message.success(res.msg)
    goSubmit()
  }
  modalVisible.value = false
}

watch(
  () => props.id,
  () => {
    if (props.title == '编辑采购申请' && props.id) getInfo()
  },
  { deep: true, immediate: true }
)

watch(
  () => route,
  async () => {
    if (route.path == '/OA/Procure/ProcureAdd') handleAmountBlur()
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 240rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    border-bottom: 1px solid #fff;
    padding: 15rem 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      flex-wrap: wrap;
      padding: 20rem 0 180rem;
      background-color: #ebeceb;


      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 5px 10rem;
          margin-bottom: 10rem;
        }
      }
    }
  }
}

.content_cen {
  display: flex;
  flex-direction: column;
  margin-left: 35%;
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}

.progress {
  display: flex;
  align-items: center;
  min-width: 350rem;
  max-width: 800rem;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  margin-bottom: 10px;
  padding: 5px 15px;
  margin-left: 35%;
}

.progressHint {
  display: flex;
  min-width: 350rem;
  max-width: 800rem;
  padding: 5px 15px;
  margin-left: 35%;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
